<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/22
 * Time: 10:49
 */
/**
 * @access public
 * @param string $value
 * @return mixed|string
 * @content 上传base64格式图片
 */
function uploadBase($value = '', $mark = false, $filename = '')
{
    if ($mark) {
        if($mark=='creation'){
            $up_dir = ROOT_PATH . 'upload/' . date("Ymd") . "/";//存放在当前目录的upload文件夹下
        }else {
            $up_dir = ROOT_PATH . 'QRCode/';
        }
    } else {
        $up_dir = ROOT_PATH . 'upload/' . date("Ymd") . "/";//存放在当前目录的upload文件夹下
    }
    $base64_img = trim($value);
//    dump($base64_img);
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
//        dump($result);
        $type = $result[2];
        if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
//            dump($up_dir);
            if (is_dir($up_dir) || mkdir($up_dir, 0755, true)) {
                if (!empty($filename)) {
                    $fileName = $filename . '.jpeg' ;
                } else {
                    $fileName = getMsectime() . getRandomString(10) . '.' . $type;
                }
                $new_file = $up_dir . $fileName;
//                dump($new_file);
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))) {
                    //$img_path = str_replace('../../..', '', $new_file);
//                    return date("Ymd") . "\\" . $fileName;
                    if ($mark) {
                        if($mark=='creation'){
                            return imgUrl(date("Ymd") . "/" . $fileName);
                        }else {
                            return $fileName;
                        }
                    } else {
                        return date("Ymd") . "/" . $fileName;
                    }
                } else {
                    return array('status' => false, 'msg' => '图片上传失败');
//                    return false;
//                return '图片上传失败';
                }
            }
        } else {
            //文件类型错误
            return array('status' => false, 'msg' => '图片文件类型错误');
//            return false;
        }
    }else{
        return $value;
    }
}

/**
 * @return float
 * @content 返回当前的毫秒时间戳
 */
function getMsectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}

/**
 * @param $len  长度
 * @param null $chars 字符集
 * @return string   对应长度的随机数字符串
 * @context 获取随机数
 */
function getRandomString($len, $chars = null)
{
    if (is_null($chars)) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
    mt_srand(10000000 * (double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}
